package com.cc.zk.distribute.zookeeper;

import com.cc.zk.SpringContextHolder;
import com.cc.zk.ZkTemplate;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;

import java.util.List;

/**
 * zk客户端
 *
 * @author cc
 * @date 2022/08/24
 */
@Slf4j
public class ZKClient {

    private static ZKClient singleton = null;

    private static final ZkTemplate ZK_TEMPLATE = SpringContextHolder.getBean(ZkTemplate.class);


    public ZKClient() {

    }

    public static ZKClient getSingleton() {
        if (null == singleton) {
            singleton = new ZKClient();

        }
        return singleton;
    }

    public CuratorFramework getClient() {
        return ZK_TEMPLATE.getClient();

    }

    /**
     * 创建 临时 顺序 节点
     */
    public String createEphemeralSeqNode(String pathPrefix) {
        return ZK_TEMPLATE.createNode(pathPrefix, "", CreateMode.EPHEMERAL_SEQUENTIAL);
    }


    /**
     * 删除当没有孩子
     *
     * @param path 路径
     */
    public void deleteWhenHasNoChildren(String path) {
        boolean exist = ZK_TEMPLATE.isNodeExist(path);
        if (exist) {
            List<String> children = ZK_TEMPLATE.getChildren(path);
            if (null != children && children.size() == 0) {
                ZK_TEMPLATE.delete(path);
                log.info("删除空的 父节点:{}", path);
            }
        }
    }

}
